package com.epam.rd.myCollections.list;

import java.util.Comparator;

public final class MyCollections {

	public static void sort(MyList myList) {
		for (int i = 0; i < myList.size(); i++) {
			for (int j = 0; j < myList.size(); j++) {
				if (((Comparable) myList.get(i)).compareTo((Comparable) myList
						.get(j)) < 0) {
					swap(myList, i, j);
				}
			}
		}
	}

	public static <T> void sort(MyList myList, Comparator comp) {

		for (int i = 0; i < myList.size(); i++) {
			for (int j = 0; j < myList.size(); j++) {
				if (comp.compare(myList.get(i), myList.get(j)) < 0) {
					swap(myList, i, j);
				}
			}
		}
	}

	public static void swap(MyList myList, int i, int j) {
		final MyList tempList = myList;
		Object temp = tempList.get(j);
		tempList.set(j, tempList.get(i));
		tempList.set(i, temp);
	}

	public static void copy(MyList sourceList, MyList destinationList) {
		destinationList.clear();
		for (Object object : sourceList) {
			destinationList.add(object);
		}
	}

	public static void reverse(MyList myList) {
		MyList tempList = new MyArrayList();
		copy(myList, tempList);
		myList.clear();
		for (Object object : tempList) {
			myList.add(0, object);
		}
		System.out.println(myList);
	}

	public static int binarySearch(
			com.epam.rd.myCollections.list.RandomAccess ra, Object i) {

		MyList list = (MyList) ra;
		int low = 0;
		int high = list.size() - 1;
		while (low <= high) {
			int mid = (low + high) >>> 1;
			System.out.println(" ");
			Comparable midVal = (Comparable) list.get(mid);
			int cmp = midVal.compareTo(i);

			if (cmp < 0) {
				low = mid + 1;
			} else if (cmp > 0) {
				high = mid - 1;
			} else {
				return mid;
			}
		}
		return -(low + 1); // key not found
	}
}
